package cn.briarbear.myblog.service.impl;

import cn.briarbear.myblog.entity.dto.AdminUserPwdModifyForm;
import cn.briarbear.myblog.entity.dto.IdListForm;
import cn.briarbear.myblog.entity.dto.UserLoginForm;
import cn.briarbear.myblog.entity.table.Admin;
import cn.briarbear.myblog.enums.ViewConsts;
import cn.briarbear.myblog.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.briarbear.myblog.repository.AdminRepository;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class AdminServiceImpl implements IAdminService {

    @Autowired
    private AdminRepository adminRepository;
    @Override
    public Admin adminLoginCheck(UserLoginForm userLoginForm) {
        String username = userLoginForm.getUsername();
        String password = DigestUtils.md5Hex(userLoginForm.getPassword());
        List<Admin> admins = adminRepository.findByUsernameAndAndPassword(username,password);
        if (admins.size()>0){
            return admins.get(0);
        }

        return null;
    }

    @Override
    public void joinSession(HttpServletRequest request, Admin admin) {
        HttpSession session = request.getSession(true);
        session.setAttribute(ViewConsts.SESSION_ADMIN_CURRENT_USER,admin);
    }

    @Override
    public void destroySession(HttpServletRequest request) {

        HttpSession session = request.getSession();
        session.removeAttribute(ViewConsts.SESSION_ADMIN_CURRENT_USER);
    }

    @Override
    public String modifyUserPwd(AdminUserPwdModifyForm form, HttpServletRequest request) {
        return null;
    }

    @Override
    public List<Admin> getAdminUsers() {
        return adminRepository.findAll();
    }

    @Override
    public void deleteAdminUser(IdListForm form) {
        for (Integer id : form.getIds()) {
            if (adminRepository.findById(id).isPresent())
                adminRepository.deleteById(id);
        }
    }
}
